import React from 'react';
import {
  Form,
  Input,
  Button,
  Table,
  Icon,
  Radio,
  InputNumber,
  Checkbox,
  Modal,
  message,
  notification,
  Affix,
  Upload,
  Select
} from 'antd';

import InnerTable from 'components/DBTable/InnerTable.js';
import loginVerify from '../../../utils/loginVerify';
import ajax from '../../../utils/ajax';

const FormItem = Form.Item;
const ButtonGroup = Button.Group;
const Option = Select.Option;

var _this;

/**
 * 内部表格组件
 */
class MuseumInnerTable extends InnerTable {

  /**
   * 构造器，好像是用来初始化的？
   * @param props
   */
  constructor(props) {
      super(props);
      this.state.moduleName = 'museum';
      this.state.museumManageUsers = [];
      this.initManageUsersData(this.props);

    }

  /**
   * 这里好像是用来配置那些按钮之类的
   * @returns {Array}
   */
  prepareToolBar = function () {

      let isButtondisabled = false;

      if (this.state.selectedRowKeys.length > 0) {  // 是否选择
        isButtondisabled = true;
      }

      if (this.state.selectedRowKeys.length > 1) {  // 是否选择了多项
        isButtondisabled = false;
      }

      var items = [];
      let permission = loginVerify.getModulePermission("MuseumManager");
      let hasDelPromission;
      for(let i=0; i<permission.length; i++){
        if(permission[i] == "delete"){
          hasDelPromission = true;
          break;
        }
      }

      if (hasDelPromission) {//权限
        if(!this.state.selectedRows[0]){ //如果没有选择
          items.push(<Button key='roleAssignBtn' type="primary" disabled={false}>
            <Icon type="user"/> 请勾选
          </Button>)
        }else{
          items.push(<Button key='recommend' type="primary" disabled={!isButtondisabled} onClick={this.onClickToRecommend}>
            <Icon type="user"/>{(!this.state.selectedRows[0].isRecommend  || this.state.selectedRows[0].isRecommend == 0 ) ? "推荐" : "取消推荐"}
          </Button>)
        }
      }


      if (this.props.tableConfig.showRoleAssign) {
        items.push(<Button key='roleAssignBtn1' type="primary" disabled={!isButtondisabled} onClick={this.onClickDisRole}>
          <Icon type="user"/>分配角色
        </Button>)
      }

      if (this.props.tableConfig.showAssignCurator) {
      items.push(<Button key='assignCuratorBtn' type="primary" disabled={!isButtondisabled} onClick={this.onClickAssignCurator}>
        <Icon type="edit"/>分配馆长
      </Button>)
    }

     return items;
  }


  /**
   * 请求数据之前,处理数据
   * @param data
   */
  handleData = (data) =>{
    data.params.ticketPrice = 0;
    data.params.tip = "如果发现地图位置或地址错误, 请联系管理人员进行修改.";
    data.params.provinceNameAndPinyin = data.params.provinceNameAndPinyin;
    data.params.aheadAppointmentDays = 7;//默认14天, 写在这里好修改...
    return data;
  }

 
  /**
   * 点击编辑
   * @param fieldsValue
   */
  dealUpdateData = (fieldsValue) =>{

    this.setState({requestSelectDefaultValue:this.state.selectedRows[0].provincePinyinFullName});
  }

  /**
   * 生成表单之前的操作
   * @param resData
   * @param field
   */
  preDealData = (resData, field) => {

    if (field.key == "provinceNameAndPinyin") {
      let requestSelectValue = this.state.requestSelectValue;

      if (!requestSelectValue) {
        //如果为空, 则去请求后台数据
        _this = this;
        ajax.post({
          url: "/search/province/listAllprovince",
          params: {},
          success: function (res) {
            if (res.data.list && res.data.list.length > 0) {
              let list = res.data.list;
              requestSelectValue = list.map((node) =>{
                return ({name : node.provinceName, value : node.provinceName + ":" + node.provincePinyinFullName});
              });
              _this.setState({requestSelectValue: requestSelectValue});
            }
          }
        })
      }
      field.requestSelectValue = requestSelectValue;
    }
  }


  onClickToRecommend = (e) =>{

    Modal.confirm({
      title:  '确认' + ((!this.state.selectedRows[0].isRecommend  || this.state.selectedRows[0].isRecommend == 0 ) ? '推荐?' : '取消推荐?'),
      content: `${this.state.selectedRows[0].name}`,
      // 这里注意要用箭头函数, 否则this不生效
      onOk: () => {
        this.handleClickToRecommend((!this.state.selectedRows[0].isRecommend  || this.state.selectedRows[0].isRecommend == 0) ? 1 : 0);
      },
    });
  }

  handleClickToRecommend = (status) =>{
    let id = this.state.selectedRowKeys[0];
    let isRecommend = status;
    _this = this;

    ajax.post({
      url: "/museummanage/recommend",
      params:{id:id, isRecommend:isRecommend},
      success: function (res) {
        if(res.errorCode==200){
          _this.props.refresh(); //刷新列表
          message.success('修改成功');
        }
      }
    });
  }


  //点击分配角色的事件
  onClickDisRole = () => {
    delete this.state.museumManageUsers;
    this.setState({ museumManageUserVisible: true });

    _this = this;
    let museumId = this.state.selectedRowKeys.join("");



    ajax.post({ // 请求数据
      url: "/museummanage/getMuseumMangeUsers",
      params: {museumId: museumId},
      success: function (res) {
        if(res.data.list && res.data.list.length >0){
          let list = res.data.list;

          //获取到新的那些option
          let newResultUser = list.map((node) => {
            return (<Option key={node.id}>{node.nick}</Option>);
          });
          _this.setState({resultUser : newResultUser});

          let ids = [];
          //添加到已有的
          for(let i=0; i< list.length ;i++){
            let userItem = {};
            userItem = list[i].id;
            ids.push(userItem);
          }
          _this.setState({museumManageUsers : ids});
          _this.setState({newMuseumManageUsers : ids});
        }
      }
    });
  }


  hideModalDisRole = () => {
    this.setState({ museumManageUserVisible: false });
  }

  onClickAssignCurator = () => {
    this.setState({ assignCuratorVisible: true });
    delete this.state.museumManageUsers;
    delete this.state.resultUser;

    _this = this;
    let museumId = this.state.selectedRowKeys.join("");

    ajax.post({ // 请求数据
      url: "/museummanage/getMuseumOrganizationUser",
      params: {museumId: museumId},
      success: function (res) {
        if(res.data.list && res.data.list.length >0){
          let list = res.data.list;

          //获取到新的那些option
          let newResultUser = list.map((node) => {
            return (<Option key={node.id}>{node.nick}</Option>);
          });
          _this.setState({resultUser : newResultUser});

          let ids = [];
          //添加到已有的
          for(let i=0; i< list.length ;i++){
            let userItem = {};
            userItem = list[i].id;
            ids.push(userItem);
          }
          _this.setState({museumManageUsers : ids});
          _this.setState({newMuseumManageUsers : ids});
        }
      }
    });
  }

  hideModalAssignCurator = () => {
    this.setState({ assignCuratorVisible: false });
  }

  updateManageUser =(value)=>{
    this.setState({ roleIds: value,roleUserChild:value});
  }



  //初始化的时候调用
  initManageUsersData = (prop) => {
  }

  /**
   * 点击确定的时候执行的操作
   */
  handleMuseumManageUserOk =()=>{
    console.log("点击确定~~~");
    let newMuseumManageUsers = this.state.newMuseumManageUsers;

    let userIds = JSON.stringify(newMuseumManageUsers);
    console.log(userIds);
    _this = this;
    ajax.post({
      url:"/museummanage/addMuseumManage",
      params:{museumId:this.state.selectedRowKeys.join(""),userIds:userIds},
      success:function(res){
        console.log(res);
        if(res.errorCode==200){
          _this.setState({ museumManageUserVisible: false});
          _this.props.refresh(); //刷新列表
          message.success('修改成功');
        }else if(res.errorCode==300){
          notification.error({
            message: '出错啦!',
            description: res.moreInfo,
            duration: 0,

          });
          _this.setState({ museumManageUserVisible: false });
        }
      }
    })
  }

  handleModalAssignCuratorOk = ()=>{
    console.log("点击确定~~~");
    let newMuseumManageUsers = this.state.newMuseumManageUsers;

    let userId = JSON.stringify(newMuseumManageUsers);
    console.log(userId);
    _this = this;
    ajax.post({
      url:"/museummanage/addOrganizationCurator",
      params:{museumId:this.state.selectedRowKeys.join(""),userId:userId},
      success:function(res){
        console.log(res);
        if(res.errorCode==200){
          _this.setState({ assignCuratorVisible: false});
          _this.props.refresh(); //刷新列表
          message.success('添加成功');
        }else if(res.errorCode==300){
          notification.error({
            message: '出错啦!',
            description: res.moreInfo,
            duration: 0,

          });
          _this.setState({ assignCuratorVisible: false });
        }
      }
    })
  }

  handleDisMuseumManageUserChange = (searchParam) => {

    if(searchParam == "" || searchParam == null) return;

    //当前已经选择过的用户
    let ids = [];
    let oldIds = this.state.museumManageUsers;
    let oldResultUserId = ""; //记住当前已经选过的那些用户id
    if(oldIds){
      console.log(oldIds);
      for(let i=0; i<oldIds.length; i++){
        ids.push(oldIds[i]);
        oldResultUserId = oldResultUserId +(oldIds[i] + ",");
      }
    }

    //当前已经选择过的那些option选项
    let resultUser = [];
    let oldResultUser = this.state.resultUser;

    if(oldResultUser){
      console.log(oldResultUser);
      for(let i=0; i<oldResultUser.length; i++){
        if(oldResultUserId.indexOf(oldResultUser[i].key) >= 0){//这里，初始化那些已经选过的option选项，将没有选中的给去除掉
          resultUser.push(oldResultUser[i]);
        }
      }
    }

    let _this = this;

    ajax.post({
      url: "/appUser/findByName",
      params: { userName: searchParam, museumId:this.state.selectedRowKeys.join("")},
      success: function (res) {
        let list = res.data.list;
        let newResultUser = list.map((temp) => {
          return (<Option key={temp.id} >{temp.nick}</Option>);
        });
        let a = 0;
        for(let i=0; i< newResultUser.length ;i++){
          if(oldResultUserId.indexOf(newResultUser[i].key) == -1){//判断是否已经包含了当前选过的用户的id，如果没有则添加
            resultUser.push(newResultUser[i]);
            a++;
          }
        }

        _this.setState({resultUser : resultUser});
      }
    })
    delete this.state.searchParam;
  }

  handleSearch =(value)=> {
    console.log("触发 本次参数是",value );
    let dateTime = Date.parse(new Date());
    this.setState({dateTime:dateTime});
    setTimeout(this.searchUser, 1000, dateTime, value);
  }

  searchUser =(dateTime, searchParam)=>{
    let stateDateTime = this.state.dateTime;
    if(dateTime == stateDateTime){
      console.log("开始请求数据, 请求参数",searchParam );
      this.handleDisMuseumManageUserChange(searchParam);
      delete this.state.dateTime;
    }
  }

  handleMuseumOrganizationUserChange = (searchParam) => {

    if(searchParam == "" || searchParam == null) return;
    let _this = this;
    ajax.post({
      url: "/museummanage/getUserInfo",
      params: { phone: searchParam},
      success: function (res) {
       let list = res.data.list;
        let newResultUser = list.map((temp) => {
          return (<Option key={temp.id} >{temp.nick}</Option>);
        });
        _this.setState({resultUser : newResultUser});
      }
    })
    delete this.state.searchParam;
  }

  curatorSearch =(value)=> {
    console.log("触发 本次参数是",value );
    let dateTime = Date.parse(new Date());
    this.setState({dateTime:dateTime});
    setTimeout(this.searchCurator, 1000, dateTime, value);
  }

  searchCurator =(dateTime, searchParam)=>{
    let stateDateTime = this.state.dateTime;
    if(dateTime == stateDateTime){
      console.log("开始请求数据, 请求参数",searchParam );
      this.handleMuseumOrganizationUserChange(searchParam);
      delete this.state.dateTime;
    }
  }

  handleChange =(value)=> {
    this.setState({museumManageUsers : value, newMuseumManageUsers : value});
  }

  curatorChange =(value)=> {
    this.setState({museumManageUsers : value, newMuseumManageUsers : value});
  }
  getUniqueModal = () => {
    return (
      <div>
        <Modal title="分配管理用户" visible={this.state.museumManageUserVisible} onOk={this.handleMuseumManageUserOk}
               onCancel={this.hideModalDisRole}>
          <Select
            multiple
            style={{ width: '100%' }}
            placeholder="请搜索要分配的用户"
            onSearch = {this.handleSearch}
            showArrow={false}
            notFoundContent="请输入用户名字"
            onChange={this.handleChange}
            value={this.state.museumManageUsers}
            defaultActiveFirstOption={false}
            filterOption={false}
          >
            {this.state.resultUser}
          </Select>
        </Modal>

        <Modal title="馆长设置" visible={this.state.assignCuratorVisible} onOk={this.handleModalAssignCuratorOk}
               onCancel={this.hideModalAssignCurator}>
            
            <Select
              multiple
              style={{ width: '100%' }}
              placeholder="请输入已注册成员手机号添加一名馆长"
              onSearch = {this.curatorSearch}
              notFoundContent="请输入电话号码"
              showArrow={false}
              onChange={this.curatorChange}
              value={this.state.museumManageUsers}
              defaultActiveFirstOption={false}
              filterOption={false}
            >
              {this.state.resultUser}
            </Select>
        </Modal>
      </div>
      
      );
  }


}

export default MuseumInnerTable;
